package com.java.base.exercise.sentinel;

/**
 * @Author RenPu
 * @Date 2022/5/1 19:13
 * @Version 1.0
 * @Description: 令牌桶限流算法
 **/
public class TokenBucket {


    public Long timeStamp = System.currentTimeMillis(); // 当前时间
    public Double capacity=100.0 ; // 桶的容量
    public Double rate= 0.5; // 令牌放入速度
    public Double tokens=0.0; // 当前令牌数量

         public boolean grant() throws InterruptedException {

          Thread.sleep(1000L);
          Long now = System.currentTimeMillis();
            double result= (tokens+((now -timeStamp)*rate));
         // 先添加令牌
         tokens = Math.min(capacity,result);
         timeStamp = now;
        if (tokens < 1) {
            // 若不到1个令牌,则拒绝
            return false;
             } else {
             // 还有令牌，领取令牌
             tokens-=1;
             return true;
             }
         }

    public static void main(String[] args) throws InterruptedException {

        TokenBucket bucket = new TokenBucket();

        for (int i = 0; i <1000 ; i++) {
            boolean grant = bucket.grant();
            if(!grant){
                System.out.println("令牌数量不足，已经被限流！！！！！");

            }
        }

    }

}
